<template>
  <div class="flex-grow-1 container-p-y" :class="layout">
    <div class="row mb-4 g-4 page-top-kb">
      <div class="col-lg-6 col-md-4 col-12 mb-md-0 mb-3">
        <el-card class="h-100">
          <div class="row">
            <div class="col-sm-5 border-shift border-end">
              <el-input placeholder="Search by create user" @keyup.enter.native="onBoxEnter" v-model="selCreateBy"></el-input>
              <h3 class="text-primary d-flex align-items-center gap-1 mb-5 mt-2"><i class="ri-money-dollar-circle-line"></i> {{$t('rent.bonus')}}</h3>
              <p class="pe-2 mb-2">{{$t('rent.bonusdesc')}}</p>
            </div>
            <div class="col-sm-7 gap-2 text-nowrap d-flex flex-column justify-content-center ps-sm-4 pt-2 py-sm-2">
              <div class="st-bitem-box">
                <div class="st-bitem" v-for="(item,idx) in leftDatas" :key="idx">
                  <span>{{item.date}}</span>
                  <!-- <el-progress :format="(p)=>{return p;}" :percentage="item.value"></el-progress> -->
                   <div class="progress-bar-box">
                      <div class="progress-bar">
                        <span class="progress-val" :style="'width:'+((item.value/100)*100)+'%'"></span>
                      </div>
                      <i class="text-val">{{parseFloat(item.value).toFixed(1)}}</i>
                   </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
      <div class="col-lg-6 col-md-8 col-12">
        <el-card class="h-100">
          <div class="row">
            <div class="col-sm-5">
              <el-input placeholder="Search by create user" @keyup.enter.native="onBoxEnter" v-model="selCreateBy"></el-input>
              <div class="mb-5">
                <h3 class="text-primary d-flex align-items-center gap-1 mb-5 mt-2"><i class="ri-list-ordered"></i>{{$t('rent.ordercnt')}}</h3>
              </div>
              <p class="pe-2 mb-2">{{$t('rent.ordercntdesc')}}</p>
            </div>
            <div class="col-sm-7 d-flex justify-content-sm-end align-items-end">
              <div class="st-bitem-column-box">
                <div class="st-bitem" v-for="(item,idx) in rightDatas" :key="idx">
                  <!-- <el-progress :format="(p)=>{return p;}" :percentage="item.value"></el-progress> -->
                   <div class="progress-bar-box">
                      <i class="text-val">{{item.value}}</i>
                      <div class="progress-bar">
                        <span class="progress-val" :style="'height:'+((item.value/100)*100)+'%'"></span>
                      </div>
                   </div>
                   <span>{{item.date}}</span>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    <el-card>
      <div class="filter-area">
        <el-form :model="form" ref="rentForm" :inline="true">
          <el-form-item :label="$t('rent.mailtype')" prop="mailTypeCode">
            <el-select :popper-append-to-body="false" filterable v-model="form.mailTypeCode" @change="handleMailTypeChange()" :placeholder="$t('page.ddlPlaceholder')"
              clearable size="small">
              <el-option v-for="item in mailTypeList" :key="item.mailTypeCode" :value="item.mailTypeCode">
                <span><img class="ddl-img-icon" :src="item.icon" alt=""> {{ item.mailTypeName }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('rent.pbcnt')" prop="platformCode">
            <el-select :popper-append-to-body="false" filterable v-model="form.platformCode" clearable size="small" :placeholder="$t('page.ddlPlaceholder')">
              <el-option v-for="item in mailPlatformList" :key="item.platformCode" :value="item.platformCode" v-if="item.platformName.indexOf('account')<0">
                <span><img class="ddl-img-icon" :src="item.icon" alt=""> {{ item.platformName }}-{{ item.bonus }}-{{
                  item.count }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="Status" prop="status">
            <el-select :popper-append-to-body="false" v-model="form.status" clearable size="small">
              <el-option label="receive" value="0"></el-option>
              <el-option label="request" value="1"></el-option>
              <el-option label="success" value="2"></el-option>
              <el-option label="account" value="3"></el-option>
            </el-select>
          </el-form-item> -->
          <el-form-item>
            <el-button type="primary" size="mini" @click="handleRent">{{$t('rent.rent')}}</el-button>
            <el-button type="info" size="mini" @click="getList">{{$t('rent.refresh')}}</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table v-loading="loading" :data="orderList" @sort-change="handleSortChange">
        <el-table-column type="selection" fixed="left" width="90" align="center" />
        <el-table-column label="ID" prop="id" v-if="false" />
        <el-table-column :label="$t('rent.orderid')" width="120px" prop="orderId" show-overflow-tooltip />
        <el-table-column :label="$t('rent.rentcost')" width="150px" prop="rentBonus">
          <template slot-scope="scope">
            <span :class="{ 'rnt-bon-r': scope.row.rentBonus < 0, 'rnt-bon-g': scope.row.rentBonus > 0 }">{{
              scope.row.rentBonus }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('rent.status')" width="150px" prop="status">
          <template slot-scope="scope">
            <span :class="['row-status', 'row-status-' + scope.row.status]">{{ statusEnum[scope.row.status] }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('rent.otp')" prop="otp" show-overflow-tooltip />
        <el-table-column :label="$t('rent.mail')" width="290px" prop="email" />
        <el-table-column :label="$t('rent.platform')" prop="platform" width="150px">
          <template slot-scope="scope">
            <span class="row-sp-has-img" v-html="platformFormat(scope.row)"></span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('rent.owner')" width="130px" prop="createBy" />
        <el-table-column :label="$t('rent.CREATETIME')" sortable="custom" prop="createTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('rent.UpdateTime')" sortable="custom" prop="updateTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>

    <Footer :layout="layout" />
    <!-- 添加或修改MailOrder对话框 -->
    <el-drawer title="MailOrder" :visible.sync="showDrawer" :size="drawerWidth" :with-header="false">
      <el-row :gutter="5" style="display: block;padding: 10px 10px 10px 20px">
        <el-button :disabled="showDrawerIndex === 1" icon="el-icon-d-arrow-left" type="primary" size="mini"
          @click="handlePrevRowClick"></el-button>
        <span style="padding:0 5px;">{{ showDrawerIndex }}（第{{ queryParams.pageNum }}页）</span>
        <el-button :disabled="showDrawerIndex === orderList.length" icon="el-icon-d-arrow-right" type="primary"
          size="mini" @click="handleNextRowClick"></el-button>
      </el-row>
      <div :style="drawerStyle">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="MailRepoID" prop="mailRepoId">
            <el-input v-model="form.mailRepoId" readonly />
          </el-form-item>
          <el-form-item label="OrderId" prop="orderId">
            <el-input v-model="form.orderId" readonly />
          </el-form-item>
          <el-form-item label="Rent Cost" prop="rentBonus">
            <el-input v-model="form.rentBonus" readonly />
          </el-form-item>
          <el-form-item label="Status">
            <el-input v-model="form.status" readonly />
          </el-form-item>
          <el-form-item label="OTP" prop="otp">
            <el-input v-model="form.otp" readonly />
          </el-form-item>
          <el-form-item label="Mail" prop="email">
            <el-input v-model="form.email" readonly />
          </el-form-item>
          <el-form-item label="Platform">
            <el-input v-model="form.platform" readonly />
          </el-form-item>
          <el-form-item label="Owner" prop="createBy">
            <el-input v-model="form.createBy" readonly />
          </el-form-item>
          <el-form-item label="Create Time" prop="createTime">
            <span>{{ parseTime(form.createTime, '{y}-{m}-{d}') }}</span>
          </el-form-item>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { listDailysummary} from "@/api/mail/dailysummary";
import ApexCharts from 'apexcharts'
import Footer from '../../../components/Footer'
import { listOrder, listOrderOtp, rentMail } from "@/api/mail/order";
import { listType } from "@/api/mail/type";
import { listTypeplatform } from "@/api/mail/typeplatform";

export default {
  components: { Footer },
  name: "Order",
  data() {
    return {
      selCreateBy:'',
      rightDatas:[],
      leftDatas:[],
      allmailPlatformList: [],
      statusEnum: {
        0: 'receive',
        1: 'request',
        2: 'success',
        3: 'account'
      },
      // 显示搜索区域
      timer: null,
      searchShow: true,
      // 显示drawer相关设置
      showDrawer: false,
      drawerWidth: document.documentElement.clientWidth < 800 ? "72%" : "67%",
      showDrawerIndex: 0,
      drawerStyle: 'overflow-y: scroll;padding: 10px;height: ' + (document.documentElement.clientHeight - 80) + 'px;',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // dialogWidth
      dialogWidth: document.documentElement.clientWidth < 800 ? "320px" : "500px",
      // 总条数
      total: 0,
      // MailOrder表格数据
      orderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // Status字典
      statusOptions: [],
      // Platform字典
      platformOptions: [],
      mailTypeList: [],
      mailPlatformList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        mailTypeCode: null,
        platformCode: null
      },
      // 表单校验
      rules: {}
    };
  },
  computed: {
    ...mapGetters([
      'name'
    ]),
    layout() {
      return localStorage.getItem('v-layout-content') || 'container-xxl';
    }
  },
  async mounted() {
    this.selCreateBy=this.name;
    let param = { pageNum: 1, pageSize: 1000 }
    let res=await listType(param);
    this.mailTypeList=res.rows;

    let _allPls=[];
    
    let promises=[];
    
    this.mailTypeList.filter((item)=>{
      let param = { pageNum: 1, pageSize: 9999, mailTypeCode: item.mailTypeCode }
      promises.push(listTypeplatform(param));
    })
    let allres=await Promise.all(promises);
    allres.map(_res=>{
      _allPls=[..._allPls,..._res.rows];
    })
    this.allmailPlatformList = _allPls;

    this.queryTopStatistics();
  },
  created() {
    window.addEventListener('resize', this.handleResize)
    this.getList();
    this.getDicts("mail_order_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_yes_no").then(response => {
      this.platformOptions = response.data;
    });

    if (this.timer == null) {
      this.timer = setInterval(() => {
        this.getList();
      }, 5000);
    }
  },
  beforeDestroy: function () {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
    window.removeEventListener('resize', this.handleResize)
  },
  methods: {
    async queryTopStatistics(){
      let res=await listDailysummary({pageNum:1,pageSize:999,type:2,createBy:this.selCreateBy});

    let day=new Date();
    let yday=new Date(new Date().setDate(day.getDate()-1));
    let yyday=new Date(new Date().setDate(yday.getDate()-1));

    console.log(this.parseTime(day,'{y}-{m}-{d}'))
    console.log(this.parseTime(yday,'{y}-{m}-{d}'))
    console.log(this.parseTime(yyday,'{y}-{m}-{d}'))

    let dayStr=this.parseTime(day,'{y}-{m}-{d}');
    let ydayStr=this.parseTime(yday,'{y}-{m}-{d}');
    let yydayStr=this.parseTime(yyday,'{y}-{m}-{d}');

    let allBonus=0,allBonus2=0,allBonus3=0,allOrderCount=0,allOrderCount2=0,allOrderCount3=0;
    res.rows.map((item)=>{
      if(item.summaryDate==dayStr)
        {
          allBonus+=item.bonus;
          allOrderCount+=item.orderNum;
        }
      else if(item.summaryDate==ydayStr)
        {
          
          allBonus2+=item.bonus;
          allOrderCount2+=item.orderNum;
        }
      else if(item.summaryDate==yydayStr)
        {
          
          allBonus3+=item.bonus;
          allOrderCount3+=item.orderNum;
        }
    })
    this.leftDatas=[{date:dayStr,value:allBonus},{date:ydayStr,value:allBonus2},{date:yydayStr,value:allBonus3}];
    this.rightDatas=[{date:dayStr,value:allOrderCount},{date:ydayStr,value:allOrderCount2},{date:yydayStr,value:allOrderCount3}];
    
    return;
    let _color = '#28c76f29';
    let _color_succ = '#28c76f';

    let options = {
      chart: {
        height: 160,
        width: 190,
        type: "bar",
        toolbar: {
          show: !1
        }
      },
      plotOptions: {
        bar: {
          barHeight: "75%",
          columnWidth: "40%",
          startingShape: "rounded",
          endingShape: "rounded",
          borderRadius: 5,
          distributed: !0
        }
      },
      grid: {
        show: !1,
        padding: {
          top: -25,
          bottom: -12
        }
      },
      colors: [_color, _color_succ, _color],
      dataLabels: {
        enabled: !1
      },
      series: [{
        data: [allOrderCount, allBonus2, allBonus3]
      }],
      legend: {
        show: !1
      },
      xaxis: {
        categories: ["T", "Y", "DBY"],
        axisBorder: {
          show: !1
        },
        axisTicks: {
          show: !1
        },
        labels: {
          style: {
            colors: '#eee',
            fontSize: "13px"
          }
        }
      },
      yaxis: {
        labels: {
          show: !1
        }
      },
      responsive: [{
        breakpoint: 0,
        options: {
          chart: {
            width: "100%"
          },
          plotOptions: {
            bar: {
              columnWidth: "40%"
            }
          }
        }
      }, {
        breakpoint: 1440,
        options: {
          chart: {
            height: 150,
            width: 190,
            toolbar: {
              show: !1
            }
          },
          plotOptions: {
            bar: {
              borderRadius: 6,
              columnWidth: "40%"
            }
          }
        }
      }, {
        breakpoint: 1400,
        options: {
          plotOptions: {
            bar: {
              borderRadius: 6,
              columnWidth: "40%"
            }
          }
        }
      }, {
        breakpoint: 1200,
        options: {
          chart: {
            height: 130,
            width: 190,
            toolbar: {
              show: !1
            }
          },
          plotOptions: {
            bar: {
              borderRadius: 6,
              columnWidth: "40%"
            }
          }
        }
      }, {
        breakpoint: 992,
        chart: {
          height: 150,
          width: 190,
          toolbar: {
            show: !1
          }
        },
        options: {
          plotOptions: {
            bar: {
              borderRadius: 5,
              columnWidth: "40%"
            }
          }
        }
      }, {
        breakpoint: 883,
        options: {
          plotOptions: {
            bar: {
              borderRadius: 5,
              columnWidth: "40%"
            }
          }
        }
      }, {
        breakpoint: 768,
        options: {
          chart: {
            height: 150,
            width: 190,
            toolbar: {
              show: !1
            }
          },
          plotOptions: {
            bar: {
              borderRadius: 4,
              columnWidth: "40%"
            }
          }
        }
      }, {
        breakpoint: 576,
        options: {
          chart: {
            width: "100%",
            height: "200",
            type: "bar"
          },
          plotOptions: {
            bar: {
              borderRadius: 6,
              columnWidth: "30% "
            }
          }
        }
      }, {
        breakpoint: 420,
        options: {
          plotOptions: {
            chart: {
              width: "100%",
              height: "200",
              type: "bar"
            },
            bar: {
              borderRadius: 3,
              columnWidth: "30%"
            }
          }
        }
      }]
    };

    new ApexCharts(document.querySelector("#barchart"), options).render();
    },
    onBoxEnter(){
        this.queryTopStatistics();
    },
    /** 查询MailOrder列表 */
    getList() {
      this.loading = true;
      // this.queryParams.orderByColumn = 'updateTime'
      // this.queryParams.isAsc = 'desc'
      listOrderOtp(this.queryParams).then(response => {
        this.orderList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // getListOtp() {
    //   this.loading = true;
    //   this.queryParams.orderByColumn = 'updateTime'
    //   this.queryParams.isAsc = 'desc'
    //   listOrderOtp(this.queryParams).then(response => {
    //     this.orderList = response.rows;
    //     this.total = response.total;
    //     this.loading = false;
    //   });
    // },
    // Status字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // Platform字典翻译
    platformFormat(row, column) {
      let item = this.allmailPlatformList.filter(r => {
        return r.platformCode == row.platform;
      });
      if (item.length > 0)
        return '<img class="row-img-icon" src="' + item[0].icon + '"/>' + item[0].platformName;
      else
        return ''
      //return this.selectDictLabel(this.platformOptions, row.platform);
    },

    /** 搜索按钮操作 */
    handleRent() {
      this.loading = true;
      const param = { "platform": this.form.platformCode, "mailTypeCode": this.form.mailTypeCode }
      rentMail(param).then(response => {
        this.loading = false;
        this.getList();
      }).catch(() => {
        this.loading = false;
      });
    },
    handleMailTypeChange() {
      const param = { pageNum: 1, pageSize: 9999, mailTypeCode: this.form.mailTypeCode }
      listTypeplatform(param).then(response => {
        this.mailPlatformList = response.rows;
        if (this.mailPlatformList.length > 0) {
          this.form.platformCode = this.mailPlatformList[0].platformCode
        }
      });
    },

    handlePrevRowClick() {
      --this.showDrawerIndex
      this.form = this.orderList[this.showDrawerIndex - 1];
    },
    handleNextRowClick() {
      ++this.showDrawerIndex
      if (this.orderList.length >= this.showDrawerIndex) {
        this.form = this.orderList[this.showDrawerIndex - 1];
      }
    },
    handleShowDetailClick(row, index) {
      this.showDrawerIndex = 1 + index
      this.form = row;
      this.showDrawer = true;
    },

    /** 弹出对话框的屏幕适应 */
    handleResize(event) {
      if (this.dialogWidth === '500px') {
        if (document.body.clientWidth < 800) {
          this.dialogWidth = "320px"
        }
      } else if (document.body.clientWidth >= 800) {
        this.dialogWidth = '500px'
      }
    },
    handleSortChange(e) {
      if (e.order === "descending") {
        this.queryParams.orderByColumn = e.prop
        this.queryParams.isAsc = 'desc'
      } else if (e.order === "ascending") {
        this.queryParams.orderByColumn = e.prop
        this.queryParams.isAsc = 'asc'
      } else {
        this.queryParams.orderByColumn = null
        this.queryParams.isAsc = null
        // this.queryParams.orderByColumn = 'updateTime'
        // this.queryParams.isAsc = 'asc'
      }
      this.getList()
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__body {
  padding: 20px 20px 5px 20px;
  border-style: solid;
  border-width: 0px 0 2px 0;
  border-color: whitesmoke;
}

::v-deep .el-dialog__footer {
  padding: 12px 20px;
}

@media (max-width: 480px) {
  ::v-deep .el-dialog__body {
    padding: 20px 20px 5px 20px;
    border-style: solid;
    border-width: 0px 0 2px 0;
    border-color: whitesmoke;
  }

  ::v-deep .el-dialog__footer {
    padding: 12px 20px;
  }

  ::v-deep .el-pagination__sizes {
    margin: 0;
  }

  ::v-deep .el-pagination .el-select .el-input {
    width: 85px;
    margin: 0;
  }

  ::v-deep .el-pagination__total {
    margin-right: 2px;
  }

  ::v-deep .el-pagination__jump {
    display: none !important;
  }
}

</style>
